package com.smtech.xz.oa;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.smtech.xz.moden.ImageBean;
import com.smtech.xz.moden.JSImage;
import com.smtech.xz.moden.ResponseImageBean;
import com.smtech.xz.netutils.OnSuccessAndFaultListener;
import com.smtech.xz.netutils.OnSuccessAndFaultSub;
import com.smtech.xz.subscribe.OaSubscribe;
import com.smtech.xz.util.ImageUtils;
import com.smtech.xz.util.JsHandler;
import com.smtech.xz.util.PhotoUtils;
import com.smtech.xz.util.SPUtils;
import com.smtech.xz.util.CrashHandler;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

import static com.smtech.xz.api.URLConstant.IMAGE_URL;
import static com.smtech.xz.api.URLConstant.SPLASH;
import static com.smtech.xz.api.URLConstant.TEST_URL2;
import static com.smtech.xz.api.URLConstant.URL;
import static com.smtech.xz.util.ImageUtils.saveNewFile;
import static com.smtech.xz.util.ImageUtils.seleteOldFile;
import static com.smtech.xz.util.SPUtils.FIRST_BOOT;
import static com.smtech.xz.util.SPUtils.IMG_URL;
import static com.smtech.xz.util.SPUtils.NET_URL;

/**
 * @author Administrator
 */
public class MainActivity extends BaseActivity {

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_CAMERA_SIGN_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private static final int LOCATION_PERMISSIONS_REQUEST_CODE = 0x05;


    private String[] mCustomItems = new String[]{"本地相册", "相机拍照"};
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    //    private String authority = "com.mst.fileprovider";
    private String authority = "com.smtech.xz.oa";

    private BridgeWebView webView;
    private Uri imageUri;
    private ValueCallback<Uri> valueUri;
    private ValueCallback<Uri[]> valueUris;

    private int backNumbers = 0;
    private boolean isPic = false;
    private boolean isSignCamera = false;

    private View errorView;
    private Context mContext;
    private RelativeLayout mainLayout;
    private String pathName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        locatePermission();

        String isSplash = null;
        if (null != getIntent().getExtras()) {
            isSplash = getIntent().getExtras().getString(SPLASH);
        }
        if (!TextUtils.isEmpty(isSplash) && isSplash.equals("2")) {
            Intent intent = new Intent(MainActivity.this, WebActivity.class);
            startActivity(intent);
        }

        mainLayout = findViewById(R.id.main_layout);

        mContext = this;
        initWebView();
        initNetData();
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
    }


    /**
     * 获取数据
     */
    private void initNetData() {
        String curPosition = "6";
        String curType = "1";
        OaSubscribe.getData(curPosition, curType, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(String result) {
                ResponseImageBean res = JSON.parseObject(result, ResponseImageBean.class);
                ImageBean bean = new ImageBean();
                if (res.getObj() != null && res.getObj().size() > 0) {
                    bean = res.getObj().get(0);
                    //截取最后的图片名称
                    String oldImgUrl = SPUtils.get(IMG_URL, "");
                    String imgurl = ImageUtils.getFileName(bean.getImgUrl());
                    //if (!TextUtils.isEmpty(bean.getImgUrl()) && !imgurl.equals(oldImgUrl))
                    {
                        saveData(bean);
                        saveNetImage(bean.getImgUrl());
                    }

                }
            }

            @Override
            public void onFault(String errorMsg) {
                //失败
                Log.i("请求失败：", errorMsg);
            }
        }));
    }

    /**
     * 保存数据
     *
     * @param bean
     */
    private void saveData(ImageBean bean) {
        pathName = ImageUtils.getFileName(bean.getImgUrl());
        SPUtils.init(this);
        SPUtils.put(IMG_URL, pathName);
        SPUtils.put(NET_URL, bean.getUrl());
        SPUtils.put(FIRST_BOOT, "1");
    }


    private void saveNetImage(String imgUrl) {
        final String url = IMAGE_URL + imgUrl;
        pathName = ImageUtils.getFileName(imgUrl);
        new SaveImgAsyncTask().execute(url);
    }

    private Handler uiHandler;

    private void initWebView() {
        webView = findViewById(R.id.web_view);
        //请尽量在设置webView属性之前调用，如果在webView属性之后调用体验可能不如这样好
        //LocationHelper.getLocationClient().startAssistantLocation(webView);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setJavaScriptEnabled(true);
        settings.setTextZoom(100);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        webView.addJavascriptInterface(new JsInterface(this), "android");

        uiHandler = new Handler(Looper.getMainLooper());

        final ArrayList<String> mHandlers = new ArrayList<>();
        mHandlers.add("smpop");
        mHandlers.add("smSaveImg");
        mHandlers.add("smshare");

        registerHandlers(mHandlers, new JsHandler() {
            @Override
            public void OnHandler(String handlerName, String data, CallBackFunction function) {
                if (handlerName.equals("smshare")) {
                    Log.i("DATA", data);
                    share(data);
                } else if (handlerName.equals("smpop")) {
                    Log.i("DATA", data);
                } else if (handlerName.equals("smSaveImg")) {
                    Log.i("DATA", data);
                    JSImage res = JSON.parseObject(data, JSImage.class);
                    if (null != res && !TextUtils.isEmpty(res.getBase64())) {
                        saveImgFile(res.getBase64());
                    }

                }
            }
        });


        settings.setDomStorageEnabled(true);

        settings.setAllowContentAccess(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        settings.setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(dir);

        settings.setGeolocationEnabled(true);
        String userAgent = settings.getUserAgentString();
        userAgent =  userAgent+ " KnxAndroidApp/1.0";
        settings.setUserAgentString(userAgent);
        // 打印结果
        Log.i("TAG", "User Agent:" + userAgent);
        Log.i("tag", Build.VERSION.RELEASE);
        webView.setWebViewClient(new MyWebViewClient(webView));
        webView.setWebChromeClient(new MyWebChromeClient());
        if (BuildConfig.DEBUG) {
            webView.loadUrl(TEST_URL2);
        } else {
            webView.loadUrl(URL);
        }
    }

    /**
     * 转码并保存成文件
     *
     * @param base64DataStr
     */
    private boolean saveImgFile(String base64DataStr) {

        // 1.去掉base64中的前缀
        String base64Str = base64DataStr.substring(base64DataStr.indexOf(",") + 1, base64DataStr.length());
        // 获取手机相册的路径地址
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        //创建文件来保存，第二个参数是文件名称，可以根据自己来命名
        File file = new File(galleryPath, System.currentTimeMillis() + ".png");
        String fileName = file.toString();
        // 3. 解析保存图片
        byte[] data = Base64.decode(base64Str, Base64.DEFAULT);

        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(fileName);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            //通知相册更新
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mContext.sendBroadcast(intent);
            Toast.makeText(mContext, "图片已保存在相册中", Toast.LENGTH_SHORT).show();

        }

    }

    /**
     * 将string转码为bitmap
     *
     * @param data
     */
    private Bitmap saveImg(String data) {

        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(data, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    public void share(String data) {
        /*
        * {
  "title": "康乃星",
  "desc": "产品不错",
  "link": "http:\/\/dev.shimutech.com.com\/hestar-vue\/register?params=vDkQqGKhBBGDS1MErJeO08iMsalOFPhMTbosmskEN\/jIOgvGoGtIQQSldrBTcBGg",
  "imgUrl": "@\/assets\/images\/404.png"
}*/
        JSONObject json;
        try {
            json = new JSONObject(data);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }
        final OnekeyShare share = new OnekeyShare();
        share.disableSSOWhenAuthorize();
        share.setTitle(json.optString("title"));
        share.setText(json.optString("desc"));
        share.setUrl(json.optString("link"));
        share.setTitleUrl(json.optString("link"));
//                share.setSiteUrl("http://dev.shimutech.com.com/hestar-vue/InvitePartners");
        share.setImageUrl(json.optString("imgUrl"));
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        share.setComment("康乃星");
//        // site是分享此内容的网站名称，仅在QQ空间使用
        share.setSite("康乃星");
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        share.setSiteUrl("www.healthstarknx.com");
        final String shareType = json.optString("shareType");
        String wechatUrlTmp = json.optString("wechatUrl");
        if(TextUtils.isEmpty(wechatUrlTmp))
            wechatUrlTmp = json.optString("link");
        final String wechatUrl = wechatUrlTmp;
        share.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {

                Log.i("tag", "wxk="+platform.getName() + platform.getId());
                if(platform.getId() ==1 || platform.getId() ==2)
                    shareParams.setUrl(wechatUrl);
//                    shareParams.setShareType(platform.SHARE_WEBPAGE);
//                else if(platform.getId() == 3)
                if(shareType == null || shareType.equals("") || shareType.equals('1'))
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                else {
                    shareParams.setTitle(null);
                    shareParams.setText(null);
                    shareParams.setSite(null);
                    shareParams.setUrl(null);
                    shareParams.setTitleUrl(null);
                    shareParams.setShareType(Platform.SHARE_IMAGE);
                }

            }
        });
        share.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.i("TAG", "share complete = :" + platform.toString());

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i("TAG", "share error = :" + platform);

            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.i("TAG", "share cancel = :" + platform);

            }
        });

        share.show(this);
    }

    private class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean loading = super.shouldOverrideUrlLoading(view, url);
            if (!loading) {
                webView.loadUrl(url);
                loading = true;
            }
            return loading;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (request.isForMainFrame()) {
                showErrorView();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }

    public void showErrorView() {
        if (errorView == null) {
            errorView = LayoutInflater.from(this).inflate(R.layout.error_view, null);
            errorView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            TextView tvReload = errorView.findViewById(R.id.btn_reload);
            tvReload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    webView.reload();
                    mainLayout.removeView(errorView);
                }
            });
        }

        mainLayout.addView(errorView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookies(null);
        cookieManager.flush();

        webView.clearCache(true);
        webView.clearHistory();
        webView.clearFormData();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        String name = getClass().getName();
        if (name.equals("com.smtech.xz.oa.WebActivity")) {
            return super.onKeyDown(keyCode, event);
        }

        backNumbers++;
        if (backNumbers < 2) {
            Toast.makeText(this, "再点一次退出App", Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    backNumbers = 0;
                }
            }, 2000);

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    //重写WebChromeClient，处理h5调起系统相机和图库、定位
    class MyWebChromeClient extends WebChromeClient {

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            valueUris = filePathCallback;
            showDialogCustom();
            return true;
        }

        public void openFileChooser(ValueCallback<Uri> filePathCallBack) {
            valueUri = filePathCallBack;
            showDialogCustom();
        }

        public void openFileChooser(ValueCallback<Uri> filePathCallBack, String acceptType) {
            valueUri = filePathCallBack;
            showDialogCustom();
        }

        public void openFileChooser(ValueCallback<Uri> filePathCallBack, String acceptType, String capture) {
            valueUri = filePathCallBack;
            showDialogCustom();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
    }

    private void showDialogCustom() {
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("请选择：");
        builder.setItems(mCustomItems, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                isPic = true;

                if (id == 0) {
                    autoObtainStoragePermission();
                } else if (id == 1) {
                    //照相机
                    autoObtainCameraPermission(CODE_CAMERA_REQUEST);
                }
            }
        });
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (!isPic) {
                    cancelPic();
                }
            }
        });
        builder.create().show();
    }

    /**
     * h5唤醒原生功能
     */
    class JsInterface {

        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        @JavascriptInterface
        public void openNativeComponent(int type) {
            switch (type) {
                case 1: //拍照
                    autoObtainCameraPermission(CODE_CAMERA_SIGN_REQUEST);
                    break;
                case 2: //摄像
                case 3: //录音
            }
        }

        @JavascriptInterface
        public void closeLocation() {
            if (LocationHelper.getLocationClient() == null) return;

            LocationHelper.getLocationClient().stopAssistantLocation();
        }

        @JavascriptInterface
        public String getLocation() {
            if (LocationHelper.getLocation() == null) {
                return "";
            }

            return LocationHelper.getLocation();
        }

        @JavascriptInterface
        public void sentLog(String data, String page) {
//            MSTMonitor.error(data, 20902, "watch", page);

        }

        @JavascriptInterface
        public void smshare(final String data) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
                }
            });
        }

        @JavascriptInterface
        public void smSaveImg(final String smpop) {
            Log.i("call back", smpop);
            System.out.println("JS调用了Android的smSaveImg方法");

//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    Toast.makeText(MainActivity.this, smpop, Toast.LENGTH_SHORT).show();
//                }
//            });
        }


        @JavascriptInterface
        public void smpop(final String data) {
            Log.i("call back", data);

//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
//                }
//            });
        }

    }

    //打开相机
    private void autoObtainCameraPermission(int requestCode) {
        isSignCamera = (requestCode == CODE_CAMERA_SIGN_REQUEST);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                //通过FileProvider创建一个content类型的Uri
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(MainActivity.this, authority, fileUri);
                }
                PhotoUtils.takePicture(this, imageUri, requestCode);
            } else {
                Toast.makeText(this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //打开图库
    private void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }

    }

    //    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
//            != PackageManager.PERMISSION_GRANTED
//                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
//            != PackageManager.PERMISSION_GRANTED
//                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
//            != PackageManager.PERMISSION_GRANTED
//                ||
    //申请权限
    private void locatePermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                            //Manifest.permission.ACCESS_COARSE_LOCATION,
                            //Manifest.permission.ACCESS_FINE_LOCATION,
                            //Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,},
                    LOCATION_PERMISSIONS_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(MainActivity.this, authority, fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        autoObtainStoragePermission();
                    }
                } else {
                    if (isSignCamera) {
                        autoObtainCameraPermission(CODE_CAMERA_SIGN_REQUEST);
                    } else {
                        autoObtainCameraPermission(CODE_CAMERA_REQUEST);
                    }
                }
                break;
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {
                    autoObtainStoragePermission();
                }
                break;
            case LOCATION_PERMISSIONS_REQUEST_CODE:
                if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == CODE_CAMERA_SIGN_REQUEST) {
            Bitmap bitmap = PhotoUtils.getBitmapFromUri2(this, imageUri);
            if (bitmap != null) {
                String bitmapData = PhotoUtils.convertBitmapToString(bitmap);
                webView.loadUrl("javascript:cameraDone(\" " + bitmapData + " \")");
                bitmap.recycle();
                imageUri = null;
            }
            return;
        }

        if (resultCode == RESULT_OK) {
            if (valueUris != null) {
                choosePicLAbove(requestCode, resultCode, data);
            } else if (valueUri != null) {
                choosePicLBelow(requestCode, resultCode, data);
            }
        } else {
            cancelPic();
        }

        isPic = false;
    }

    private void cancelPic() {
        if (valueUri != null) {
            valueUri.onReceiveValue(null);
            valueUri = null;
        }

        if (valueUris != null) {
            valueUris.onReceiveValue(null);
            valueUris = null;
        }
    }

    // <5.0 以下回调
    private void choosePicLBelow(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //拍照完成回调
                case CODE_CAMERA_REQUEST:
                    valueUri.onReceiveValue(imageUri);
                    break;
                //访问相册完成回调
                case CODE_GALLERY_REQUEST:
                    if (hasSdcard()) {
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            newUri = FileProvider.getUriForFile(this, authority, new File(newUri.getPath()));
                        }

                        valueUri.onReceiveValue(newUri);
                    } else {
                        Toast.makeText(this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        } else {
            valueUri.onReceiveValue(null);
        }

        valueUri = null;
    }

    //  >=5.0 以上的回调
    private void choosePicLAbove(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //拍照完成回调
                case CODE_CAMERA_REQUEST:
                    valueUris.onReceiveValue(new Uri[]{imageUri});
                    break;
                //访问相册完成回调
                case CODE_GALLERY_REQUEST:
                    if (hasSdcard()) {
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            newUri = FileProvider.getUriForFile(this, authority, new File(newUri.getPath()));
                        }

                        valueUris.onReceiveValue(new Uri[]{newUri});
                    } else {
                        Toast.makeText(this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        } else {
            valueUris.onReceiveValue(null);
        }

        valueUris = null;
    }

    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 批量注册本地java方法，以供js端调用
     *
     * @param handlerNames 方法名称数组
     * @param handler      回调接口
     */
    public void registerHandlers(final ArrayList<String> handlerNames, final JsHandler handler) {
        if (handler != null) {
            for (final String handlerName : handlerNames) {
                webView.registerHandler(handlerName, new BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        handler.OnHandler(handlerName, data, function);
                    }
                });
            }
        }
    }

    /**
     * 下载图片
     */
    class SaveImgAsyncTask extends AsyncTask<String, Void, File> {

        @Override
        protected File doInBackground(String... params) {
            try {
                File sourceFile = Glide.with(mContext).asFile().load(params[0]).submit().get();
                Log.i("path", "path-->" + sourceFile.getPath());
                seleteOldFile();
                saveNewFile(mContext, sourceFile, pathName);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
        }
    }

}
